package bsr.basara.autodata.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;

@Slf4j
public class CommonUtils {

    /**
     * 当前系统数据库类型
     */
    private static String DB_TYPE = "";

    public static String getDbType() {
        if (StrUtil.isNotEmpty(DB_TYPE)) {
            return DB_TYPE;
        }
        DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
        return getDbTypeByDataSource(dataSource);
    }

    /**
     * 获取数据库类型
     *
     * @param dataSource
     */
    public static String getDbTypeByDataSource(DataSource dataSource) {
        if ("".equals(DB_TYPE)) {
            try (Connection connection = dataSource.getConnection()) {
                DatabaseMetaData md = connection.getMetaData();
                String dbType = md.getDatabaseProductName().toLowerCase();
                if (dbType.contains("mysql")) {
                    DB_TYPE = "mysql";
                } else if (dbType.contains("dm")) {
                    DB_TYPE = "dm";
                } else if (dbType.contains("oracle")) {
                    DB_TYPE = "oracle";
                } else if (dbType.contains("sqlserver") || dbType.contains("sql server")) {
                    DB_TYPE = "sqlserver";
                } else if (dbType.contains("postgresql")) {
                    DB_TYPE = "postgresql";
                } else {
                    log.error("数据库类型:[" + dbType + "]不识别!");
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return DB_TYPE;
    }
}
